import type { AppRouteRecordRaw, Menu } from '@/router/types';

import { defineStore } from 'pinia';
import { store } from '@/store';
import { getMenuList } from '@/apis/sys/menu';
import { setAuthCache } from '@/utils/auth';
import { AUTH_CODE_LIST } from '@/enums/app-enum';

interface PermissionState {
  // Backstage menu list
  // 后台菜单列表
  menuList: Menu[];
}

export const usePermissionStore = defineStore({
  id: 'app-permission',
  state: (): PermissionState => ({
    // Backstage menu list
    // 后台菜单列表
    menuList: []
  }),
  getters: {
    getMenuList(state): Menu[] {
      return state.menuList || [];
    }
  },
  actions: {
    setMenuList(list: any[]) {
      this.menuList = list || [];
    },
    resetState(): void {
      this.menuList = [];
    },
    // 构建路由
    async getMenuData() {
      // code
      const authCodeList: string | number[] = [];
      const routeRemoveIgnoreFilter = (route: AppRouteRecordRaw) => {
        const { type, buttonMode, isVisible, menuCode } = route;
        if (menuCode) {
          authCodeList.push(menuCode);
        }
        // arr.filter 返回 true 表示该元素通过测试
        return type === 'menu' && buttonMode !== '2' && isVisible === '1';
      };
      /**
       * @description 修正数据
       * */
      const transformRouters = (routes: any) => {
        return routes.filter(routeRemoveIgnoreFilter).map((route: any) => {
          const { path: fullPath, menuCode, menuName: name, children = [], menuIcon, id } = route;
          const currentRoute = {
            ...route,
            fullPath,
            icon: menuIcon,
            name: menuCode,
            path: fullPath || id,
            children: children && children.length && transformRouters(children),
            meta: {
              title: name
            }
          };
          return currentRoute;
        });
      };

      let menuList: AppRouteRecordRaw[] = [];
      try {
        const menuData = (await getMenuList()) as AppRouteRecordRaw[];
        menuList = transformRouters(menuData || []);
        setAuthCache(AUTH_CODE_LIST, authCodeList);
        this.setMenuList(menuList);
      } catch (error) {
        console.error(error);
      }
    }
  }
});

// Need to be used outside the setup
// 需要在设置之外使用
export function usePermissionStoreWithOut() {
  return usePermissionStore(store);
}
